import React, { useRef, useState, forwardRef, useMemo, useImperativeHandle, useEffect } from 'react';
import { Image,Upload } from '@douyinfe/semi-ui';
import { useSelector, useDispatch } from 'react-redux';
import { selectCurrentVideo, setCurrentVideo } from '@/store';
import add from "@/assets/images/imageEdit/add.svg";
import styles from "./index.module.scss";
import CanvasDrawing from './CanvasDrawing';
import { useVideoUpload } from '@/hooks/useVideoUpload';
import { UPLOAD_CONFIG } from './constants';

const Results = forwardRef(({ 
  selectedTool,
  toolSize,
  onPointSelectionChange, // 点选变化回调
  onGreenPointSelectionChange, // 绿色点变化回调
  onBrushStrokesChange, // 画笔笔触变化回调
  onRectSelectionChange, // 框选变化回调
  onStepChange,
  step, // 步骤值
  selectedPreviewMode, // 预览模式
  currentVideo: propsCurrentVideo, // 从props传入的当前视频
  previewVideoUrl, // 预览视频URL
  currentVideoTime, // 当前视频时间
  isVideoPlaying, // 视频播放状态
  onVideoTimeUpdate, // 视频时间更新回调
  videoLoadError, // 视频加载错误状态
  onVideoLoadError, // 视频加载错误状态更新回调
}, ref) => {
  const dispatch = useDispatch();
  const canvasDrawingRef = useRef(null);
  const videoWrapperRef = useRef(null); // 视频容器ref
  const previewVideoRef = useRef(null); // 分割结果预览视频ref
  const currentVideo = useSelector(selectCurrentVideo) || propsCurrentVideo;
  
  // 当预览视频URL变化时，重置加载错误状态
  useEffect(() => {
    if (previewVideoUrl && onVideoLoadError) {
      onVideoLoadError(false);
    }
  }, [previewVideoUrl, onVideoLoadError]);
  
  // 同步分割结果预览视频的时间和播放状态
  useEffect(() => {
    if (previewVideoRef.current && selectedPreviewMode === 'result') {
      const previewVideo = previewVideoRef.current;
      
      // 同步时间
      if (Math.abs(previewVideo.currentTime - currentVideoTime) > 0.1) {
        previewVideo.currentTime = currentVideoTime;
      }
      
      // 同步播放状态
      if (isVideoPlaying && previewVideo.paused) {
        previewVideo.play().catch(console.error);
      } else if (!isVideoPlaying && !previewVideo.paused) {
        previewVideo.pause();
      }
    }
    
    // 当切换到原视频模式时，暂停预览视频
    if (previewVideoRef.current && selectedPreviewMode === 'original') {
      const previewVideo = previewVideoRef.current;
      if (!previewVideo.paused) {
        previewVideo.pause();
      }
    }
  }, [currentVideoTime, isVideoPlaying, selectedPreviewMode]);

  const { handleUpload, uploading, progress, validateFile, uploadedFile } = useVideoUpload({
    onSuccess: async (result) => {
      onStepChange(1);
      
      // 设置当前视频URL到store
      dispatch(setCurrentVideo(result.url));
      console.log('视频上传成功，URL:', result.url);
    },
    onError: (error) => {
      console.error('上传失败:', error);
    }
  });
   

  
  // 图片编辑相关状态
  const [showCanvas, setShowCanvas] = useState(true); // 控制Canvas显示状态
  const [mediaTransform, setMediaTransform] = useState({
    layerStyles: {}
  }); // 媒体变换状态
  
  // 注意：现在使用视频上传时获取的尺寸信息，不再需要从DOM元素获取图片尺寸
  
  // 根据selectedTool计算eraseMode
  const eraseMode = useMemo(() => {
    switch(selectedTool) {
      case 'press': return 4; // 点选模式
      case 'brush': return 2; // 画笔模式
      case 'graphic': return 5; // 框选/橡皮擦模式
      default: return 1;
    }
  }, [selectedTool]);

  // 暴露方法给父组件
  useImperativeHandle(ref, () => ({
    clearCanvas: () => {
      if (canvasDrawingRef.current?.clearBrushStrokes) {
        canvasDrawingRef.current.clearBrushStrokes();
      }
    },
    getCanvasImage: () => {
      if (canvasDrawingRef.current?.getCanvasImage) {
        return canvasDrawingRef.current.getCanvasImage();
      }
      return null;
    },
    handleDownloadResizedImage: () => {
      if (canvasDrawingRef.current?.handleDownloadResizedImage) {
        return canvasDrawingRef.current.handleDownloadResizedImage();
      } else {
        console.error('CanvasDrawing组件的handleDownloadResizedImage方法不可用');
      }
    },
    setSelectedImage: (imageKey) => {
      if (canvasDrawingRef.current?.setSelectedImage) {
        canvasDrawingRef.current.setSelectedImage(imageKey);
      }
    }
  }), []);

  return (
    <div className={styles.results} ref={ref} style={{position: 'relative'}}>
      <div 
        className={styles.area}
        style={{ paddingRight: '8px',display:step>0?'none':'flex' }}
      >
        <div className={styles.layerItem}>
          <Upload 
            {...UPLOAD_CONFIG} 
            className={`${styles.uploadSection} ${styles.uploadFullSize}` }  
            customRequest={async ({ file, onSuccess, onError }) => {
              try {
                const isValid = await validateFile(file);
                if (!isValid) {
                  onError?.(new Error('文件验证失败'));
                  return;
                }
                
                // 执行上传
                const result = await handleUpload(file, file.name);
                
                if (result.success) {
                  onSuccess?.(result);
                } else {
                  onError?.(result.error || new Error('上传失败'));
                }
              } catch (error) {
                console.error('上传失败:', error);
                onError?.(error);
              }
            }}
            disabled={uploading}
            onAcceptInvalid={() => {
              Toast.error({ content: '文件类型不支持，请重新选择文件', stack: true });
            }}
          >
          <div className={styles.uploadPlaceholder}>
            {uploading ? (
              <div className={styles.uploadingState}>
                <div className={styles.uploadText}>上传中... {progress}%</div>
                <div className={styles.progressBar} style={{ width: `${progress}%` }}></div>
              </div>
            ) : (
              <>
                <Image
                  src={add}
                  preview={false}
                  className={styles.uploadIcon}
                  draggable={false}
                />
                <div className={styles.uploadText}>
                  点击或拖拽上传
                </div>
              </>
            )}
          </div>
          </Upload>
        </div>
      </div>
      {currentVideo&&<div className={styles.resultsSingle} style={{position: 'absolute',zIndex:'10'}}>
        {/* 分割结果预览模式下显示的视频 */}
        {selectedPreviewMode=='result'&&<div style={{
          position: 'absolute',
          top: 0,
          left: 0,
          width: '100%',
          height: '100%',
          zIndex: 100,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          backgroundColor: '#000'
        }}>
          {previewVideoUrl && !videoLoadError ? (
            <video
              id="preview-video"
              ref={previewVideoRef}
              src={previewVideoUrl}
              style={{
                width: '100%',
                height: '100%',
                objectFit: 'contain'
              }}
              muted
              playsInline
              preload="metadata"
              onTimeUpdate={(e) => {
                if (onVideoTimeUpdate) {
                  onVideoTimeUpdate(e.target.currentTime);
                }
              }}
              onLoadedData={() => {
                console.log('Preview video loaded');
                if (onVideoLoadError) {
                  onVideoLoadError(false);
                }
              }}
              onError={(e) => {
                console.error('Preview video error:', e);
                if (onVideoLoadError) {
                  onVideoLoadError(true);
                }
              }}
            />
          ) : (
            <div style={{
              color: '#fff',
              fontSize: '16px',
              textAlign: 'center',
              padding: '20px'
            }}>
              <div style={{ marginBottom: '10px' }}>📹</div>
              <div>暂无预览视频</div>
              <div style={{ fontSize: '14px', opacity: 0.7, marginTop: '5px' }}>
                {!previewVideoUrl ? '请先选择已处理完成的片段' : '视频加载失败'}
              </div>
            </div>
          )}
        </div>}
        <div ref={videoWrapperRef} style={{width:'100%',height:'100%',position: 'relative',overflow: 'hidden'}}>
          <CanvasDrawing 
            ref={canvasDrawingRef}
            eraseMode={eraseMode}
            toolSize={toolSize}
            onMediaStyleChange={setMediaTransform} // 接收样式变化通知
            onPointSelectionChange={onPointSelectionChange} // 点选变化回调
            onGreenPointSelectionChange={onGreenPointSelectionChange} // 绿色点变化回调
            onBrushStrokesChange={onBrushStrokesChange} // 画笔笔触变化回调
            onRectSelectionChange={onRectSelectionChange} // 框选变化回调
            hideDisplayCanvas={!showCanvas} // 控制显示Canvas的可见性，但保留离屏Canvas
            mediaWrapperRef={videoWrapperRef} // 传递视频容器ref
            mediaElementId="current-video" // 媒体元素ID
            enableProcessing={true} // 根据当前菜单键决定是否启用处理功能
          />
          <div id="current-video" style={{position:'absolute',width:'100%',height:'100%',zIndex:1}}>
            <video
              className={styles.video}
              src={currentVideo} 
              crossOrigin="anonymous"
              muted
              playsInline
              preload="metadata"
              style={{
                ...mediaTransform,
                transform: `${mediaTransform.transform || ''}`,
                position: 'absolute',
                zIndex: 1,
                width: '100%',
                height: '100%',
                objectFit: 'contain',
                pointerEvents: 'auto'
              }}
            />
          </div>
        </div>
      </div>}
    </div>
  );
});

Results.displayName = 'Results';

export default Results;